package com.jshan.task;

import com.jshan.base.entity.SysServer;
import com.jshan.service.SysServerService;
import com.jshan.utils.ServerMonitorUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class ServerStatusScheduler {

    private final SysServerService serverService;
    private final ServerMonitorUtils serverMonitorUtils;

    /**
     * 每分钟执行一次服务器状态检查
     */
    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void checkServerStatus() {
        log.info("开始检查服务器状态...");
        List<SysServer> servers = serverService.list();

        for (SysServer server : servers) {
            try {
                boolean isOnline = serverMonitorUtils.isServerOnline(server.getIp(), server.getPort());
                Integer newStatus = isOnline ? 1 : 0;
                if (server.getStatus() == null || !server.getStatus().equals(newStatus)) {
                    server.setStatus(newStatus);
                    serverService.updateById(server);
                    log.info("服务器 {} 状态已更新为: {}", server.getName(), isOnline ? "在线" : "离线");
                }
            } catch (Exception e) {
                log.error("检查服务器 {} 状态时发生错误: {}", server.getName(), e.getMessage());
            }
        }
        log.info("服务器状态检查完成");
    }
}
